package com.sundaying.gooway.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.sundaying.gooway.dao.UserDao;
import com.sundaying.gooway.entity.User;

@Component("userDao")
public class UserDaoImpl implements UserDao {
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource(name = "sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public int save(User obj) {
		int result = 0;
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save(obj);
		session.getTransaction().commit();
		session.close();
		sessionFactory.close();
		result = 1;
		return result;
	}

	@Override
	public int update(User obj) {
		int result = 0;
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.update(obj);
		session.getTransaction().commit();
		session.close();
		sessionFactory.close();
		result = 1;
		return result;
	}

	@Override
	public int delete(User obj) {
		int result = 0;
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.delete(obj);
		session.getTransaction().commit();
		session.close();
		sessionFactory.close();
		result = 1;
		return result;
	}

	@Override
	public User load(int id) {
		User user = null;
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		user = (User) session.load(User.class, id);
		session.getTransaction().commit();
		session.close();
		return user;
	}

	@Override
	public List<User> list() {
		List<User> userList = null;
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Query query = session.createQuery("from User u");
		userList = (List<User>) query.list();
		session.getTransaction().commit();
		session.close();
		return userList;
	}

	@Override
	public List<User> list(String hsql, List<Object> param) {
		List<User> userList = null;
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Query query = session.createQuery(hsql);
		if (param != null && param.size() > 0) {
			int size = param.size();
			for (int i = 0; i < size; i++) {
				query.setParameter(i, param.get(i));
			}
		}

		userList = (List<User>) query.list();
		session.getTransaction().commit();
		session.close();
		return userList;
	}

	@Override
	public List<User> list(String hsql, List<Object> param, int page, int rows) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long count(String hql, List<Object> param) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	
}
